<template>
  <div class="rich-datetime-wrapper">
    <el-input v-model="inputValue" readonly>
      <template slot="append">
        <el-button @click="openDatetimePicker('datetime')">时间点</el-button>
        <el-button @click="openDatetimePicker('datetimerange')">时间范围</el-button>
      </template>
    </el-input>
    <el-date-picker
      :picker-options="pickerOptions"
      ref="selectedDatetime"
      v-if="showDatetimePicker"
      v-model="selectedDatetime"
      :value-format="valueFormat"
      :type="type"
      @change="handleDatetimeChange"
      @blur="handleDatetimeBlur"
      class="custom-datetime"
    ></el-date-picker>
    <el-date-picker
      :picker-options="pickerOptions"
      ref="selectedDatetimeRange"
      v-if="showDatetimeRangePicker"
      v-model="selectedDatetimeRange"
      :value-format="valueFormat"
      :type="type + 'range'"
      @change="handleDatetimeRangeChange"
      @blur="handleDatetimeRangeBlur"
      class="custom-datetime"
    ></el-date-picker>
  </div>
</template>

<script>
export default {
  name: 'RichDate',
  props: {
    type: {
      type: String,
      default: 'date', // date, datetime
    },
    valueFormat: {
      type: String,
      default: 'yyyy-MM-dd', // yyyy-MM-dd, yyyy-MM-dd HH:mm:ss
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(v) {
          // return v.getTime() < new Date().getTime() - 86400000;
          return ''
        }
      },
      inputValue: '',
      showDatetimePicker: false,
      showDatetimeRangePicker: false,
      selectedDatetime: '',
      selectedDatetimeRange: '',
    };
  },
  methods: {
    openDatetimePicker(type) {
      if (type === 'datetime') {
        this.showDatetimePicker = true;
        this.$nextTick(() => {
          this.$refs.selectedDatetime.focus();
        })
      } else if (type === 'datetimerange') {
        this.showDatetimeRangePicker = true;
        this.$nextTick(() => {
          this.$refs.selectedDatetimeRange.focus();
        })
      }
    },
    handleDatetimeBlur() {
      this.showDatetimePicker = false;
    },
    handleDatetimeRangeBlur() {
      this.showDatetimeRangePicker = false;
    },
    handleDatetimeChange(value) {
      this.showDatetimePicker = false;
      this.inputValue = value;
      this.$emit('input', value);
    },
    handleDatetimeRangeChange(value) {
      this.showDatetimeRangePicker = false;

      if (value && value.length) {
        this.inputValue = value.join(',');
      }

      this.$emit('input', value);
    },
  },
};
</script>
<style lang="scss" scoped>
.rich-datetime-wrapper {
  .custom-datetime {
    position: relative;
    top: -33px;

    ::v-deep .el-input__inner {
      border: none;
    }
  }
}
</style>
